package javango.contrib.admin.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javango.contrib.admin.ModelManager;
import javango.contrib.hibernate.HibernateUtil;
import javango.contrib.hibernate.ModelDao;

import org.hibernate.mapping.PersistentClass;

/**
 * Subclasses should override the constructor calling addClass or addClasses to build the list of classes that can be managed via the admin interface
 * @param clazz
 */
public class CustomAdminOptions implements AdminOptions {

	List<PersistentClass> classList = new ArrayList<PersistentClass>();
	Map<Class, ModelManager> managers = new HashMap<Class, ModelManager>();
	
	HibernateUtil hibernateUtil;
	
	public CustomAdminOptions(HibernateUtil hibernateUtil) {
		this.hibernateUtil = hibernateUtil;
	}

	protected void addClasses(Class... classes) {
		for(Class c : classes) {
			addClass(c);
		}
	}

	
	protected void addClass(Class clazz) {
		this.classList.add(hibernateUtil.getConfiguration().getClassMapping(clazz.getName()));
	}
	
	public PersistentClass getClassMapping(String entityName) {
		for(PersistentClass c : classList) {
			if (c.getClassName().equals(entityName)) {
				return c;
			}
		}
		return null;
	}

	public Iterator<PersistentClass> getClassMappings() {
		return classList.iterator();
	}

	public ModelManager<?> getManager(Class entityClass) {
		if (managers.containsKey(entityClass)) {
			return managers.get(entityClass);
		}
		
		return new javango.contrib.admin.BaseModelManager(entityClass, new ModelDao(hibernateUtil, entityClass));
	}

	
}
